package net.ipinglun.module.newsDetail;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.orhanobut.hawk.Hawk;

import net.ipinglun.module.newsList.GetNewsListResponseHandler;
import net.ipinglun.module.newsList.NewsBean;
import net.ipinglun.module.newsList.NewsListBean;
import net.ipinglun.util.BasePresenter;
import net.ipinglun.util.HttpHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class NewsDetailPresenter extends BasePresenter {

    private static final String TAG = "NewsDetail";

    public void getNewsDetail(String newsId, final GetNewsDetailResponseHandler handler) {

        String url = "http://api.wallstreetcn.com/v2/posts/" + newsId;

        handler.onStart();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        NewsDetailBean newsDetail = new NewsDetailBean();

                        try {

                            newsDetail.title = response.getString("title");

                            String body = response.getString("content");
                            String html = "<html><link href='file:///android_asset/style.css' rel='stylesheet' type='text/css'/><head><title></title></head><body style='color:#333333;line-height:150%%;font-size:16px;'>body_content</body></html>";

                            newsDetail.content = html.replaceAll("body_content",  body).replaceAll("style=\"[^/]+px;\"", "");
                            //System.out.println("html=" + newsDetail.content);


                        } catch (JSONException e) {

                        }

                        handler.onSuccess(newsDetail);
                        handler.onFinish();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        handler.onFailure();
                        handler.onFinish();
                    }
                }
        );

        jsonObjectRequest.setRetryPolicy(new
                        DefaultRetryPolicy(HttpHelper.TIME_OUT,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        HttpHelper.getInstance().addToRequestQueue(jsonObjectRequest, TAG);

    }
}
